#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import urllib2
import urllib
import sys
import codecs

sys.stdout = codecs.getwriter('utf_8')(sys.stdout)

#URLを解析し、現在利用可能なクーポン番号を取得
html = urllib.urlopen('http://www.mcdonalds.co.jp/sales/new/smileplus/index.php').read().decode('shift-jis', 'ignore')

a = html.split('\n')
cNums = []

import re
for i in a:
    rex = re.split('name=\'coupon\[\]\' value=\'', i)
    if len(rex) > 2:
        for j in rex[1:]:
            cNum = j[0:3]
            cNums.append(cNum if cNum[2] != '\'' else cNum[0:2])

#クーポン番号を元に画像を取得
box = 0, 0, 223, 180

def saveImg(url, fn):
    try:
        buffer = urllib.urlopen(url).read()
        image = Image.open(StringIO(buffer))
        image.save(fn+'.png')
        print fn+'.png'
        thumb = image.crop(box)
        thumb.save(fn+'_thumb.png')
        print fn+'_thumb.png'
    except:
        print url + " exception."
import Image
import urllib
from cStringIO import StringIO

url = "http://img.mcdonalds.co.jp/sales/new/smileplus/img/cp/coupon%s.gif"

#for u in cNums:
#    saveImg(url % u, u)


#htmlの出力

template = u"""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>iUI Music Demo</title>
<meta name="viewport" content="charset=UTF-8; width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<style type="text/css" media="screen">@import "./iui/iui/iui.css";</style>
<script type="application/x-javascript" src="./iui/iui/iui.js"></script>
<!--
<script type="application/x-javascript" src="http://10.0.1.2:1840/ibug.js"></script>
-->
</head>

<body onclick="console.log('Hello', event.target);">
    <div class="toolbar">
        <h1 id="pageTitle"></h1>
        <a id="backButton" class="button" href="#"></a>
        <a class="button" href="#about">about</a>
    </div>
    <div id="about" title="about" class="panel">
    see <a href = "http://code.google.com/p/mcdonaldscoupon/">http://code.google.com/p/mcdonaldscoupon/</a>
    </div>
    <ul id="home" title="McdonaldsCoupon" selected="true">
        %s
    </ul>
    %s

</body>
</html>
"""

listT = """<li><a href="#%s"><img src="%s"></a></li>
"""

detailT = """
    <div id="%s" title="%s" class="panel">
    <img src="%s">
    </div>
"""

details = ""
lists = ""

for u in cNums:
    lists += listT % (u, u+"_thumb.png")
    details += detailT % (u, u, u+".png")

fp = open('McDonaldsCoupon.html', 'w')
fp.write(template % (lists, details))
fp.close()



